package cn.wolfcode.luowowo.service.impl;


import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionObjcet;
import cn.wolfcode.luowowo.repository.DestinationRepository;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {


    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private MongoTemplate template;
    @Override
    public Region get(String id) {
        return  regionRepository.findById(id).orElse(null);
    }

    @Override
    public Page<Region> query(RegionObjcet qo) {
        //创建查询对象
        Query query = new Query();
        //分页查询
        long count = template.count(query, Region.class);
        if(count == 0){
            return Page.empty();
        }
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        //添加条件
        query.with(pageable);
        List<Region> list = template.find(query, Region.class);
        return new PageImpl<Region>(list,pageable,count);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }



    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(region.getId()==null){
            this.save(region);
        }else{
            this.update(region);
        }
    }

    @Override
    public void changeHotValue(int hot, String id) {
        Query query = new Query();
        //根据ID选出哪一个ID需要变动
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot",hot);
        template.updateMulti(query, update, Region.class);

    }

    @Override
    public List<Region> hotRegion() {

        return regionRepository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
    }


}
